package com.wn.common.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import com.wn.common.ktx.viewDataBind

/**
 * @Author: wn
 * @Date: 2022/12/8 15:41
 * @Description: 抽象的公用 BaseFragment
 * viewpager2 默认实现懒加载  onResume
 */
abstract class BaseFragment<T : ViewDataBinding> : Fragment {
  constructor() : super()
  constructor(@LayoutRes layout: Int) : super(layout)

  protected lateinit var mBinding: T

  @LayoutRes
  protected abstract fun getLayoutRes(): Int

  // 子类 重写  获取 dataBinding
//  abstract fun viewDataBind(view: View, savedInstanceState: Bundle?): T

  // open 可以被重写  protected 可以被访问
  // 初始化配置
  protected open fun initConfig() {}

  // 初始化视图
  protected open fun initView() {}

  // 初始化数据
  protected open fun initData() {}

  // 懒加载数据
  protected open fun initLazyData() {}

  override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?,
  ): View? {

//    mBinding = viewDataBind(inflater, container) // 继承时需要指定 泛型
    mBinding = viewDataBind(getLayoutRes(), container)
//    return inflater.inflate(getLayoutRes(), container, false)
    return mBinding.root
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    //将binding对象和view关联到一起
    mBinding.lifecycleOwner = viewLifecycleOwner
    initView()
    initData()
    initConfig()
  }

  /**
   * viewPager2 实现懒加载的 方式
   */
  override fun onResume() {
    super.onResume()
    initLazyData()
  }

  override fun onDestroyView() {
    super.onDestroyView()
    //此处记得取消绑定，避免内存泄露
    if (::mBinding.isInitialized) {
      mBinding.unbind()
    }
  }

  /*
   * 扩展liveData的observer函数
   * */
  protected inline fun <T> LiveData<T>.observeKt(crossinline block: (T?) -> Unit) {
    observe(viewLifecycleOwner) {
//      block(it)
      it.also(block)
    }
  }
}


